package com.lotto.manager.admin.daemon;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.lotto.manager.admin.dao.KitheMapper;
import com.lotto.manager.admin.entity.db.Kithe;
import com.lotto.manager.admin.system.SystemData;
import com.lotto.manager.common.constant.SystemConstant;

@Component
public class KitheDaemon extends Thread {
	
	private long waitTime = 2L * 1000;
	// 日志对象
	private Logger log = Logger.getLogger(KitheDaemon.class);
	
	@Autowired
	KitheMapper kitheMapper;
	
	@Override
	public void run() {

		while (true) {
			try {
				disposeKithe();
				Thread.sleep(waitTime);
			} catch (Exception e) {
				log.error("系统自动处理期号数据出错", e);
			}
		}
	}
	
	/**
	 * 
	* 方法名称: disposeKithe
	* 描述:如果有变化数据则将数据更新到缓存中。
	* 参数： 
	* @throws
	 */
	private void disposeKithe(){
		Kithe lastKithe = SystemData.getLastKithen();
		if(null == lastKithe){
			lastKithe = new Kithe();
			lastKithe.setLastTime(new Date(1));
			lastKithe.setKitheStatus(SystemConstant.KITHE_STATUS_SUCCEED);
		}
		Kithe kithe = kitheMapper.selectChange(lastKithe);
		if(null != kithe){
			findAllKithen();
		}
	}
	
	private void findAllKithen(){
		Kithe Kithe = new Kithe();
		Kithe.setLastTime(new Date(1));
		Kithe.setKitheStatus(SystemConstant.KITHE_STATUS_SUCCEED);
		List<Kithe> list = kitheMapper.selectList(Kithe);
		if(null == list || 0 == list.size()) return;
		/*SystemData.setKithens(list); */
		Kithe lastKithe = list.get(0);
		for(int i=1;i<list.size();i++){
			Kithe temKithe = list.get(i);
			if(temKithe.getLastTime().getTime()>lastKithe.getLastTime().getTime()){
				lastKithe = temKithe;
			}
		}
		SystemData.setLastKithen(lastKithe);
		int tosize = list.size();
		SystemData.maxentries = tosize;
		int page = tosize/SystemConstant.KITHE_PER_PAGE;
		for(int i=0;i<=page;i++){
			List<Kithe> pageKithes = new ArrayList<Kithe>();
			for(int j=0;j<SystemConstant.KITHE_PER_PAGE && (i*SystemConstant.KITHE_PER_PAGE+j)<list.size();j++){
				pageKithes.add(list.get(i*SystemConstant.KITHE_PER_PAGE+j));
			}
			SystemData.addHistoryList((i), pageKithes);
		}
		
		/*List<Kithe>tmeList = SystemData.getPageKitheList(1);
		for(Kithe k :tmeList){
			System.out.println(k.getKitheId());
		}
		List<Kithe>tmeList2 = SystemData.getPageKitheList(2);
		for(Kithe k :tmeList2){
			System.out.println(k.getKitheId());
		}
		List<Kithe>tmeList3 = SystemData.getPageKitheList(3);
		for(Kithe k :tmeList3){
			System.out.println(k.getKitheId());
		}*/
	}



}
